<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Models\Orders;
use App\Events\WeChatNoticeEvent;
use Illuminate\Support\Facades\Redis;
class Charge extends Command
{
    protected $orders;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order_charge';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'order_charge';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Orders $orders)
    {
        parent::__construct();
        $this->orders = $orders;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ordersn = Redis::rpop('order_refund');
        if($ordersn){
            $orders = $this->orders->where('ordersn', $ordersn)->first();
            if(in_array(optional($orders)->order_status,[3,4]) && optional($orders)->refund_status == 0){
                    // 判断订单是否自动退款还是手动退款
                if(in_array(optional($orders)->freight_status,[3,4,5,6])){
                    $machine = DB::table('machines')->where('imei',$orders->machines_imel)->where('is_auto_refund',1)->first(); 
                    if($machine){
                        if($orders){
                            $refundOrderSn = $this->refundOrderSn();
                            $data = array(
                                'goodsid' => $orders->goodsid,
                                'userid' => $orders->user_id,
                                'ordersn' => $orders->ordersn,
                                'refund_ordersn' => $refundOrderSn,
                                'return_num' => 1,
                                'created_at' => date('Y-m-d H:i:s', time()),
                                'updated_at' => date('Y-m-d H:i:s', time()),
                            );
                            $refundsId = DB::table('refunds')->insertGetId($data);
                            if($refundsId){
                                $merchantInfo = DB::table('merchant_orders')
                                ->leftJoin('users_codes', 'users_codes.merchant_id', '=', 'merchant_orders.merchant_id')
                                ->select('users_codes.customerNum', 'users_codes.shopNum', 'users_codes.shopAccess', 'users_codes.shopSecret')
                                ->where('order_id', $orders->id)
                                ->first();
                                $pay = new \App\Http\Controllers\Api\PayOrderController;
                                //判断ordersn是否为主订单
                                $index_char = substr($orders->ordersn, 0, 1);
                                $ordersn = $index_char == 'Z' ? substr($orders->ordersn,0,-2) : $orders->ordersn;
                                $refundPartAmount = $orders->order_total_price;
                                $result = $pay->refundDLBPay($ordersn, $refundOrderSn, $merchantInfo, $refundPartAmount);
                                if('success' == $result['result']){
                                    $manager = DB::table('manager_third_auths')
                                    ->leftJoin('merchant_orders','merchant_orders.merchant_id','=','manager_third_auths.manager_id')
                                    ->where('merchant_orders.order_id',$orders->id)
                                    ->first();
                                    if($manager){
                                        if($manager->push_type){
                                            $push = json_decode($manager->push_type,1);
                                            $ispush = $push['lack']['val'];
                                            if($ispush){
                                                // 推送
                                                //退款通知订单中加入总订单号 总金额
                                                $msg = '退款通知 -- 单号：'.$ordersn.' 金额：'.$refundPartAmount;
                                                event(new WeChatNoticeEvent($manager->wx_open_id, $msg));
                                            }
                                        }
                                    }
                                    $this->orders->where('ordersn', $orders->ordersn)->update(['refund_status' => 2]);
                                
                                } 
                            }
                        }
                    }
                }
            }            
        }
    }

    // 生成订单SN
    protected function refundOrderSn()
    {
        $orderSn = '';
        $orderSn = 'HRCTK_';
        $orderSn .= date('YmdHis');
        $orderSn .= mt_rand(1, 99999);
        return $orderSn;
    }
}
